<template>
  <div
    ref="search"
    :style="{paddingBottom:(($store.state.player.showPlayerUi&&!$store.state.player.miniUi)?'60px':'0px')}"
    class="search-content"
  >
    <transition name="van-fade">
      <div v-show="pageUILoadEnd" class="search-header">
        <span @click="onBack" class="header-icon-back" tag="div">
          《《《
        </span>
        <input
          @keyup.13="onConfirm"
          v-model="inputModel"
          class="header-input"
          type="text"
        >
        <van-icon v-show="inputModel" @click="onCloseSearch" class="header-icon-closed" name="wap-home-o" size="24" />
      </div>
    </transition>
    <!-- tabs -->
    <van-tabs ref="tabs" @click="onTab" v-model="tabActive">
      <!-- 歌曲 -->
      <van-tab title="歌曲">
        <van-list
          v-if="songList&&songList.length>0"
          v-model="loading"
          :finished="songListFinished"
          @load="onLoad(tabActive)"
          :immediate-check="false"
          loading-text
          finished-text="--- end ---"
          class="songs-content content"
        >
          <li v-for="(item, index) in songList" @click="onClickSong(item.id)" :key="index">
            <p v-text="item.name" class="song-name" />
            <p class="song-des">
              <span v-if="item.artists[0].name" v-text="item.artists[0].name" />
              <span v-if="item.alias[0]" v-text="' - '+item.alias[0]" />
              <span v-if="item.album.name" v-text="' - '+item.album.name" />
            </p>
          </li>
        </van-list>
      </van-tab>
      <!-- 视频 -->
      <van-tab title="视频">
        <van-list
          v-if="videoList&&videoList.length>0"
          v-model="loading"
          :finished="videoListFinished"
          @load="onLoad(tabActive)"
          :immediate-check="false"
          loading-text
          finished-text="--- end ---"
          class="videas-content content"
        >
          <li v-for="(item, index) in videoList" @click="onClickVideoList(item.vid)" :key="index">
            <img :src="item.coverUrl" :alt="item.vid">
            <div>
              <p v-if="item.title" class="video-title">
                {{ item.title }}
              </p>
              <p v-if="item.creator[0]" class="video-author">
                {{ item.creator[0].userName }}
              </p>
            </div>
          </li>
        </van-list>
      </van-tab>
      <!-- 歌单 -->
      <van-tab title="歌单">
        <van-list
          v-if="playList&&playList.length>0"
          v-model="loading"
          :finished="playListFinished"
          @load="onLoad(tabActive)"
          :immediate-check="false"
          loading-text
          finished-text="--- end ---"
          class="plays-content content"
        >
          <li v-for="(item, index) in playList" @click="onClickPlayList(item.id)" :key="index">
            <img v-if="item.coverImgUrl" :src="item.coverImgUrl" alt="smusic img" class="playlist-icon">
            <p v-text="item.name" class="plays-name" />
            <p v-text="item.creator.nickname||item.description" class="plays-des" />
          </li>
        </van-list>
      </van-tab>
    </van-tabs>
    <!-- totop -->
    <div @click="goToTop" v-show="offsetY > 100" class="top-icon">
      <van-icon name="down" size="24" />
    </div>
  </div>
</template>

<script>
import { search } from '@/utils/api/search'
import { songDetailList } from '@/utils/api/song'
// eslint-disable-next-line no-unused-vars
import { getSearchPlayList, saveSearchPlayList, clearLastSearchPlayList } from '@/utils/localStorage'
import { pageMixin } from '@/utils/mixin'

export default {
  mixins: [pageMixin],
  head () {
    return {
      title: 'smusic 搜索: ' + this.inputModel,
      meta: [
        { hid: 'description', name: 'smusic', content: 'smusic 歌曲 视频 歌单相关 - ' + this.inputModel }
      ]
    }
  },
  data () {
    return {
      pageUILoadEnd: false, // 标记页面骨架结构初始化完成
      offsetY: 0,
      loading: false,
      tabActive: 0,
      defaultSearchLimit: 10, // 默认搜索limit限制
      // 歌曲
      songTabOffsetY: 0, // tab 滚动位置记录
      // 视频
      videoList: [],
      videoListOffset: 0,
      videoListFinished: false, // 标记加载当前关键字搜索的视频数据加载完成
      videoTabOffsetY: 0, // tab 滚动位置记录
      // 歌单
      playList: [],
      playListOffset: 0,
      playListFinished: false, // 标记加载当前关键字搜索的歌单数据加载完成
      playTabOffsetY: 0 // tab 滚动位置记录
    }
  },
  computed: {
    historyList () {
      return this.$store.state.search.historyList
    }
  },
  watch: {
    async '$route' (to, from) {
      if (to.query.word !== from.query.word) {
        // 手动重置页面数据状态,再发送请求获取数据
        clearLastSearchPlayList()
        this.trySetTabScrollY()
        this.resetPageAllDataStatus(to.query.word)
        await this.getSongList()
      }
    }
  },
  async asyncData ({ ctx, params, query }) {
    const word = query.word
    if (!word) {
      return {
        inputModel: word,
        songList: [],
        songListOffset: 0,
        songListFinished: false
      }
    }
    try {
      const searchRes = await search(encodeURI(word), 1, 0, 20)
      const _songList = searchRes.data.result.songs
      const _songListFinished = _songList.length > searchRes.data.result.songCount
      return {
        inputModel: word,
        songList: _songList,
        songListOffset: _songList.length,
        songListFinished: _songListFinished
      }
    } catch (error) {
      return {
        inputModel: word,
        songList: [],
        songListOffset: 0,
        songListFinished: false
      }
    }
  },
  beforeRouteEnter (to, from, next) {
    next(async (vm) => {
      // 当前页-> 歌单详情/视频播放页 ->当前页
      // 处理记录回滚
      if (from.name === 'listDetail-id' && to.name === 'search') {
        // 调回当前页
        vm.tabActive = 2
        const res = getSearchPlayList()
        const _offsetY = res.offsety
        const _listOffset = res.listOffset
        const _defaultSearchLimit = vm.defaultSearchLimit
        vm.defaultSearchLimit = _listOffset // 取item加载过的记录
        vm.playList = [] // 清空
        await vm.getPlayList()
        vm.inputModel = res.word
        vm.defaultSearchLimit = _defaultSearchLimit // 还原
        vm.trySetTabScrollY(_offsetY) // 滚动
        return
      }
      if (to.name === 'search') {
        // 当前页刷新的话 清除各自记录
        clearLastSearchPlayList()
      }
    })
  },
  mounted () {
    // mounted 手动触发一次获取历史搜索
    this.$store.commit('search/setHistoryList', '')
    // 给第三方 van-tab 加class
    this.setVantTabDomFixed()
    // 监听滚动
    window.addEventListener('scroll', this.handleScrollY)
    this.pageUILoadEnd = true
  },
  beforeDestroy () {
    window.removeEventListener('scroll', this.handleScrollY)
  },
  methods: {
    resetPageAllDataStatus (word = '') {
      // 手动重置页面的所有数据状态
      this.inputModel = word
      this.offsetY = 0
      this.loading = false
      this.tabActive = 0
      this.songList = []
      this.songListOffset = 0
      this.songListFinished = false
      this.defaultSearchLimit = 10
      this.songTabOffsetY = 0
      this.videoList = []
      this.videoListOffset = 0
      this.videoListFinished = false
      this.videoTabOffsetY = 0
      this.playList = []
      this.playListOffset = 0
      this.playListFinished = false
      this.playTabOffsetY = 0
    },
    async setVantTabDomFixed () {
      // 每次打开页面 需要给vant-ui-tab 添加元素 控制固定位置
      await this.$nextTick()
      const dom = this.$refs.tabs.$el.children[0]
      dom.classList.add('van-tabs__wrap-new-class')
    },
    onCloseSearch () {
      // 回到首页
      clearLastSearchPlayList()
      this.$store.commit('search/setShowSearchPanel', false)
      this.$router.push({ path: '/' })
    },
    handleScrollY () {
      const scrollTop = window.pageYOffset || document.body.scrollTop || document.documentElement.scrollTop
      if (this.tabActive === 0) { this.songTabOffsetY = this.offsetY = scrollTop }
      if (this.tabActive === 1) { this.videoTabOffsetY = this.offsetY = scrollTop }
      if (this.tabActive === 2) { this.playTabOffsetY = this.offsetY = scrollTop }
    },
    onBack () {
      // 返回上一页
      this.$router.go(-1)
    },
    goToTop () {
      this.trySetTabScrollY()
    },
    trySetTabScrollY (y = 0) {
      // 设置滚动位置
      // eslint-disable-next-line no-console
      console.log('重新设置滚动位置: ' + y)
      document.documentElement.scrollTop = y
    },
    onClickSong (id) {
      // 点击某一歌曲
      if (id) {
        // 尝试播放单曲
        this.getSongListDetail([id])
      }
    },
    onClickPlayList (id) {
      // 点击某 歌单
      if (id) {
        this.$toast(id)
        this.$router.push({ path: `/listDetail/${id}` })
        // 尝试保存某些状态,当我点击返回时 需要滚回搜索记录的
        saveSearchPlayList(this.inputModel, this.playListOffset, this.playTabOffsetY)
      }
    },
    onClickVideoList (id) {
      // 点击某 个视频
      if (id) {
        this.$toast(id)
        this.$router.push({ path: `/video?id=${id}` })
        // 尝试保存某些状态,当我点击返回时 需要滚回搜索记录的
      }
    },
    onConfirm () {
      if (!this.inputModel) {
        return
      }
      // 跳转到搜索结果页
      this.$router.push({ path: `/search`, query: { word: this.inputModel } })
      // 添加搜索记录
      this.$store.commit('search/setHistoryList', this.inputModel)
    },
    async onTab (index) {
      //  切换tab栏
      if (this.tabActive !== index) {
        this.loading = false
        this.tabActive = index
      }
      if (this.tabActive === 0) {
        // 歌曲
        this.trySetTabScrollY(this.songTabOffsetY)
        this.songList.length === 0 && await this.getSongList()
      } else if (this.tabActive === 1) {
        // 视频
        this.trySetTabScrollY(this.videoTabOffsetY)
        this.videoList.length === 0 && await this.getVideoList()
      } else if (this.tabActive === 2) {
        // 歌单
        this.trySetTabScrollY(this.playTabOffsetY)
        this.playList.length === 0 && await this.getPlayList()
      }
    },
    async onLoad (index) {
      // 加载更多
      index === 0 && await this.getSongList()
      index === 1 && await this.getVideoList()
      index === 2 && await this.getPlayList()
    },
    async getSongList () {
      // 搜索歌曲列表
      if (this.inputModel !== this.historyList[0]) {
        // 新的关键字搜索
        this.songList = []
        this.songListOffset = 0
      }
      try {
        const res = await search(this.inputModel, 1, this.songListOffset, 15)
        if (res.data && res.data.code === 200 && res.data.result) {
          this.songList.push(...res.data.result.songs)
          // this.songList = [...this.songList, ...res.data.result.songs]
          this.songListOffset += res.data.result.songs.length
          if (this.songListOffset >= res.data.result.songCount) {
            this.songListFinished = true
          }
        }
      } catch (error) {
        // eslint-disable-next-line no-console
        if (error.code === 'ECONNABORTED' && error.message.includes('timeout')) {
          this.httpTimeOut()
        }
      }
      this.loading = false
    },
    async getVideoList () {
      // 搜索视频列表
      if (this.inputModel !== this.historyList[0]) {
        // 新的关键字搜索
        this.videoList = []
        this.videoListOffset = 0
      }
      try {
        const res = await search(this.inputModel, 1014, this.videoListOffset, this.defaultSearchLimit)
        if (res.data && res.data.code === 200 && res.data.result) {
          this.videoList = [...this.videoList, ...res.data.result.videos]
          this.videoListOffset += res.data.result.videos.length
          if (this.videoListOffset >= res.data.result.videoCount) {
            this.videoListFinished = true
          }
        }
      } catch (error) {
        // eslint-disable-next-line no-console
        if (error.code === 'ECONNABORTED' && error.message.includes('timeout')) {
          this.httpTimeOut()
        }
      }
      this.loading = false
    },
    async getPlayList () {
      // 搜索 歌单 列表
      if (this.inputModel !== this.historyList[0]) {
        // 新的关键字搜索
        this.playList = []
        this.playListOffset = 0
      }
      try {
        const res = await search(this.inputModel, 1000, this.playListOffset, this.defaultSearchLimit)
        if (res.data && res.data.code === 200 && res.data.result) {
          this.playList.push(...res.data.result.playlists)
          // this.playList = [...this.playList, ...res.data.result.playlists]
          this.playListOffset += res.data.result.playlists.length
          if (this.playListOffset >= res.data.result.playlistCount) {
            this.playListFinished = true
          }
        }
      } catch (error) {
        // eslint-disable-next-line no-console
        if (error.code === 'ECONNABORTED' && error.message.includes('timeout')) {
          this.httpTimeOut()
        }
      }
      this.loading = false
    },
    async getSongListDetail (ids) {
      // 根据歌曲id获取歌曲信息
      let list
      try {
        list = await songDetailList(ids)
        if (list.data.code !== 200) {
          this.$toast('找不到音乐')
          return
        }
      } catch (error) {
        return
      }
      // 查看当前播放列表是否存在
      this.$store.commit('player/setCurrentPlayerList', list.data.songs)
      this.$store.commit('player/setCurrentPlayObj', list.data.songs[0])
      // eslint-disable-next-line no-console
      console.log(list.data.songs[0])
      // 展开播放器组件
      setTimeout(() => {
        this.$store.commit('player/setShowPlayerUi', true)
        this.$store.commit('player/setMiniUi', false) // 小屏展示
      }, 300)
    }
  }
}
</script>

<style lang="scss" scoped>
@import "@/assets/style/global.scss";

.search-content {
  width: 100%;
  height: 100%;
  background: #fff;
  position: relative;
  /deep/.van-tabs__wrap {
    border-bottom: 1PX solid rgba(0,0,0,.05);
    box-shadow: 2PX 2PX 2px rgba(0,0,0,.05);
    width: 100%;
    height: 36px;
  }
  /deep/.van-tab--active {
    color: #ee0a24;
  }
  /deep/.van-tabs__wrap-new-class {
    position: fixed;
    top: 47px;
    left: 0;
    z-index: 100;
  }
  /deep/.van-list {
    list-style: none;
  }
  /deep/.van-tabs__content {
    padding-top: 96px;
  }
  .search-header {
    position: fixed;
    top: 0;
    left: 0;
    z-index: 99;
    width: 100%;
    height: 48px;
    padding-bottom: 2px;
    background: #fff;
    display: flex;
    justify-content: space-around;
    align-items: center;
    .header-input {
      flex: 1;
      height: 38px;
      margin-left: 18px;
      margin-right: 4px;
      padding-left: 6px;
      outline: none;
      border: none;
      border-bottom: 1px solid rgba(0,0,0,.1);
    }
    .header-icon-closed {
      width: 40px;
      height: 36px;
      line-height: 36px;
      text-align: center;
    }
  }
  .top-icon {
    position: fixed;
    z-index: 100;
    bottom: 72px;
    right: 32px;
    width: 36px;
    height: 36px;
    line-height: 45px;
    text-align: center;
    transform: rotate(180deg);
    -webkit-transform: rotate(180deg);
    background: rgba(10, 10, 10, 0.5);
    border-radius: 50%;
  }
  .content {
    li{
      p {
        @include ellipsis;
      }
    }
  }
  .songs-content {
    width: 100%;
    padding: 0 20px;
    &.li:last-child {
      border-bottom: none;
    }
    li {
      height: 48px;
      margin-top: 10px;
      border-bottom: 1PX solid rgba(0,0,0,.05);
      .song-name {
        font-size: 16px;
      }
      .song-des {
        font-size: 12px;
        color: #666;
      }
    }
  }
  .videas-content {
    width: 100%;
    padding: 0 20px;
    &.li:last-child {
      border-bottom: none;
    }
    li {
      height: 108px;
      display: flex;
      align-items: center;
      border-bottom: 1PX solid rgba(0,0,0,0.05);
      img {
        width: 128px;
        height: 72px;
        border-radius: 6px;
      }
      div {
        padding-left: 6px;
        .video-title {
          font-size: 16px;
          @include ellipsis(2);
        }
        .video-author {
          margin-top: 4px;
          font-size: 12px;
          color: #666;
        }
      }
    }
  }
  .plays-content {
    width: 100%;
    padding: 0 20px;
    &.li:last-child {
      margin-top: 10px;
      border-bottom: none;
    }
    li {
      height: 72px;
      border-bottom: 1PX solid rgba(0,0,0,.05);
      position: relative;
      .playlist-icon {
        width: 48px;
        height: 48px;
        position: absolute;
        top: 7px;
        left: 0;
        border-radius: 50%;
        box-sizing: border-box;
      }
      .plays-name {
        font-size: 16px;
        padding-left: 56px;
        padding-Top: 16px;
      }
      .plays-des {
        font-size: 12px;
        padding-left: 56px;
        color: #666;
      }
    }
  }
}
</style>
